package com.rxst.msg.sso.entity;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.rxst.msg.entity.MsgxUserEntity;
import com.rxst.msg.vo.menu.MenuFunctionVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * 当前用户信息
 *
 * @author rxst
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UserContext {

    private static final ThreadLocal<UserContext> USER_CONTEXT_THREAD_LOCAL = new ThreadLocal();
    /**
     * 用户信息
     */
    private MsgxUserEntity user;
    /**
     * token
     */
    private String token;
    /**
     * token
     */
    private String random;
    /**
     * 菜单信息
     */
    private List<MenuFunctionVo> menuList;
    /**
     * 菜单信息
     */
    private List<String> menuUrlList;
    /**
     * 用户ID
     */
    private String userId;

    /**
     * 添加用户信息
     *
     * @param userContext
     */
    public static void setLocalUserContext(UserContext userContext) {
        USER_CONTEXT_THREAD_LOCAL.set(userContext);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public static UserContext getUserContext() {
        return (UserContext) USER_CONTEXT_THREAD_LOCAL.get();
    }

    /**
     * 移除用户信息
     */
    public static void removeUserContext() {
        USER_CONTEXT_THREAD_LOCAL.remove();
    }

    /**
     * 获取用户ID
     *
     * @return
     */
    public String getCurrentUserId() {
        UserContext userContext = getUserContext();
        if (userContext != null && userContext.getUser() != null) {
            return userContext.getUser().getUserId();
        }
        return null;
    }

    /**
     * 校验url是否有访问权限
     *
     * @param url
     * @return
     */
    public boolean authMenu(String url) {
        if (StrUtil.isBlank(url)) {
            return false;
        }
        List<String> menuUrlList = getMenuUrlList();
        if (CollUtil.isEmpty(menuUrlList)) {
            return false;
        }
        return menuUrlList.contains(url);
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}
